import { ChatContext, ChatContextProvider } from '@/app/chat-context';
import SideBar from '@/components/layout/side-bar';
// import FloatHelper from '@/new-components/layout/FloatHelper';
import PageCornerLogo from '@/new-components/common/PageCornerLogo';
import { STORAGE_LANG_KEY, STORAGE_USERINFO_KEY, STORAGE_USERINFO_USER_PATH_MENUS } from '@/utils/constants/index';
import { App, ConfigProvider, MappingAlgorithm, theme } from 'antd';
import enUS from 'antd/locale/en_US';
import zhCN from 'antd/locale/zh_CN';
import classNames from 'classnames';
import type { AppProps } from 'next/app';
import Head from 'next/head';
import { useRouter } from 'next/router';
import React, { useContext, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import '../app/i18n';
import '../nprogress.css';
import '../styles/globals.css';
import PageLoading from '@/components/layout/page-loading';
import { RouteConfig } from '@/types/router';
import useUser from '@/hooks/use-user';

const antdDarkTheme: MappingAlgorithm = (seedToken, mapToken) => {
  return {
    ...theme.darkAlgorithm(seedToken, mapToken),
    colorBgBase: '#232734',
    colorBorder: '#828282',
    colorBgContainer: '#232734',
  };
};

function CssWrapper({ children }: { children: React.ReactElement }) {
  const { mode } = useContext(ChatContext);
  const { i18n } = useTranslation();

  useEffect(() => {
    if (mode) {
      document.body?.classList?.add(mode);
      if (mode === 'light') {
        document.body?.classList?.remove('dark');
      } else {
        document.body?.classList?.remove('light');
      }
    }
  }, [mode]);

  useEffect(() => {
    i18n.changeLanguage?.(window.localStorage.getItem(STORAGE_LANG_KEY) || 'zh');
  }, [i18n]);

  return (
    <div>
      {children}
    </div>
  );
}

function LayoutWrapper({ children }: { children: React.ReactNode }) {
  const { isMenuExpand, mode,handleUserInfoChange } = useContext(ChatContext);
  const { i18n } = useTranslation();
  const [isLogin, setIsLogin] = useState(false);

  const router = useRouter();
  const { pathname } = useRouter();

  // 登录检测
  const handleAuth = async () => {
    setIsLogin(false);
    //登录后的操作
    const userInfo = useUser();
    const menusPathAry: RouteConfig = JSON.parse(localStorage.getItem(STORAGE_USERINFO_USER_PATH_MENUS) || '[]');

    const baseRoutes = ["/login","/moreAnalysis_setting"];
    const allowedRoutes = ['/userInfoSetting','/moreAnalysis_setting', ...menusPathAry];
    const currentRoute = router.pathname;
    const isLogin = baseRoutes.includes(currentRoute);
    const isNoahX = allowedRoutes.includes(currentRoute) && userInfo?.access_token;
    if (isLogin || isNoahX) {
      setIsLogin(true);
    } else {
      setIsLogin(true);
      localStorage.clear();
      sessionStorage.clear();
      router.push('/login');
    }
    // console.log('isLogin || isNoahX', currentRoute,isLogin , isNoahX)
  };

  useEffect(() => {
    handleAuth();
  }, [router.pathname]);

  if (!isLogin) {
    return null;
  }

  const renderContent = () => {
    if (router.pathname.includes('mobile')) {
      return <>{children}</>;
    }
    return (
      <div className='flex w-screen h-screen overflow-hidden welcome-bg'>
        <Head>
          <meta name='viewport' content='initial-scale=1.0, width=device-width, maximum-scale=1' />
        </Head>
        {router.pathname !== '/construct/app/extra' &&
         router.pathname !== '/login' &&
         router.pathname !== '/moreAnalysis_setting' &&
        (
          <div className={classNames('transition-[width]', isMenuExpand ? 'w-60' : 'w-20', 'hidden', 'md:block')}>
            <SideBar />
          </div>
        )}
        <div className='flex flex-col flex-1 relative overflow-hidden'>{children}</div>
        {<PageCornerLogo />}
      </div>
    );
  };

  return (
    <ConfigProvider
      locale={i18n.language === 'en' ? enUS : zhCN}
      theme={{
        token: {
          colorPrimary: '#8665FF',
          borderRadius: 4,
        },
        algorithm: mode === 'dark' ? antdDarkTheme : undefined,
      }}
    >
      <App>{renderContent()}</App>
    </ConfigProvider>
  );
}

function MyApp({ Component, pageProps }: AppProps) {

  const router = useRouter();
  const isLoginPage = router.pathname === '/login';

  if (isLoginPage) {
    return <Component {...pageProps} />;
  }
  return (
    <>
      <PageLoading />
      <ChatContextProvider>
        <CssWrapper>
          <LayoutWrapper>
            <Component {...pageProps} />
          </LayoutWrapper>
        </CssWrapper>
      </ChatContextProvider>
    </>
  );
}

export default MyApp;
